package org.vsaulyak.springrssagregator.controller;

import java.util.Map;
import javax.inject.Inject;
import javax.validation.Valid;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.vsaulyak.springrssagregator.entity.Chanel;
import org.vsaulyak.springrssagregator.bean.ChanelHandler;
import org.vsaulyak.springrssagregator.exception.AppropriateParserNotFoundException;

@Controller
@RequestMapping({"/", "/home"})
public class ChanelHandlerController 
{
    @Inject
    private ChanelHandler chanelHandler;
    
    @RequestMapping(method = RequestMethod.GET)
    public String showChanelsPage(ModelMap model)
    {
        model.put("chanel", new Chanel());
        model.put("chanels", chanelHandler.getChanels());
        return "chanels";
    }
    
    @RequestMapping(method = RequestMethod.POST)
    public String handlePostRequest(@Valid final Chanel chanel, final BindingResult bindingResult) {
        if (bindingResult.hasErrors())
        {
            return "chanels";
        }
        try
        {
            chanelHandler.parseItems(chanel);
        }
        catch (AppropriateParserNotFoundException e)
        {
            return "exception";
        }
        
        return "success";
    }
    
    public ChanelHandler getChanelHandler()
    {
        return chanelHandler;
    }
    
    public void setChanelHandler(ChanelHandler chanelHandler)
    {
        this.chanelHandler = chanelHandler;
    }
}
